/**
 * 
 */
package com.padbot.qm.rest;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

import javax.security.sasl.AuthenticationException;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.padbot.qm.client.PadbotHttpClientUtil;
import com.padbot.qm.exception.SystemException;
import com.padbot.qm.oss.OssBackup;
import com.padbot.qm.security.UserSessionBean;
import com.padbot.qm.security.UserSessionTokenUtils;
import com.padbot.qm.util.Constants;
import com.padbot.qm.util.Md5Encoder;

/**
 * @author Deng
 *
 */
@Path("/rest")
public class PadbotqmRestService {
	
	private static Logger logger = LoggerFactory.getLogger(PadbotqmRestService.class);
	
	private OssBackup ossBackup = new OssBackup();
	
	public PadbotqmRestService(){
		
	}
	
	@POST
	@Path("/loginByAccount")
	@Produces("application/json; charset=utf-8")
	public Response loginByAccount(String loginInfo){
		long startTime = System.currentTimeMillis();
		logger.debug("Login by account...");
		JSONObject result = new JSONObject();
		JSONObject param = JSONObject.parseObject(loginInfo);
		try{
			String pass = Md5Encoder.encoding(param.getString("password"));
			param.put("password", pass);
//			result = JSONObject.parseObject("{\"messageCode\": \"10000\",\"user\":{\"id\": \"afda807e53ae69a40153c05f69d200dc\",\"nickname\":\"张三\",\"username\":\"zhangsan\"}}");
			result = PadbotHttpClientUtil.loginByAccount(param);
			if(Constants.SUCCESS_CODE.equals(result.getString("messageCode"))){
				JSONObject userJson = result.getJSONObject("user");
				UserSessionBean userSessionBean = UserSessionTokenUtils.setUserSession(
					userJson.getString("id"), userJson.getString("username"), userJson.getString("nickname"));
				userJson.put("token", userSessionBean.getTokenKey());
			}
		}catch(SystemException e){
			logger.error(e.getMessage(), e);
			result.put("messageCode", "90002");
		}catch(Exception e){
			logger.error("调用后台服务失败, 未知错误", e);
			result.put("messageCode", "90002");
		}
		result.put("messageText", Constants.get(result.getString("messageCode")));
		long endTime = System.currentTimeMillis();
		logger.debug("Login finished, time:"+(endTime-startTime));
		return Response.status(200).entity(result.toJSONString()).build();
	}
	
	@POST
	@Path("/loginByQr")
	@Produces("application/json; charset=utf-8")
	public Response loginByQr(String loginInfo){
		long startTime = System.currentTimeMillis();
		logger.debug("Login by account...");
		JSONObject result = new JSONObject();
		try{
			result = PadbotHttpClientUtil.loginByQr(JSONObject.parseObject(loginInfo));
			if(Constants.SUCCESS_CODE.equals(result.getString("messageCode"))){
				JSONObject userJson = result.getJSONObject("user");
				UserSessionBean userSessionBean = UserSessionTokenUtils.setUserSession(
						userJson.getString("id"), userJson.getString("username"), userJson.getString("nickname"));
				userJson.put("token", userSessionBean.getTokenKey());
			}
		}catch(SystemException e){
			logger.error(e.getMessage(), e);
			result.put("messageCode", "90002");
		}catch(Exception e){
			logger.error("调用后台服务失败, 未知错误", e);
			result.put("messageCode", "90002");
		}
		result.put("messageText", Constants.get(result.getString("messageCode")));
		long endTime = System.currentTimeMillis();
		logger.debug("Login finished, time:"+(endTime-startTime));
		return Response.status(200).entity(result.toJSONString()).build();
	}
	
	@POST
	@Path("/{servName}/{methodName}")
	@Produces("application/json; charset=utf-8")
	public Response post(@PathParam("servName") String servName, 
			@PathParam("methodName") String methodName,
			@HeaderParam("token") String token,
			String requestBody) {
		long startTime = System.currentTimeMillis();
		logger.debug("Access post function");
		logger.debug("Access token is:"+token);
		JSONObject result = new JSONObject();
		JSONObject param = JSONObject.parseObject(requestBody);
		try{
			if(!"getQrCode.action".equals(methodName)){
				//检查是否登录
				logger.debug("Authority.....");
				if(!UserSessionTokenUtils.isActive(token)){
					throw new AuthenticationException();
				}
			}
			logger.debug("Call remote function....");
			if("updateUserPassword.action".equals(methodName)){
				String oldPass = Md5Encoder.encoding(param.getString("oldPassword"));
				param.put("oldPassword", oldPass);
				String newPass = Md5Encoder.encoding(param.getString("newPassword"));
				param.put("newPassword", newPass);
				result = PadbotHttpClientUtil.post(servName, methodName, param);
			}else{
				result = PadbotHttpClientUtil.post(servName, methodName, JSONObject.parseObject(requestBody));
			}
		}catch (AuthenticationException e) {
			logger.error(e.getMessage(), e);
			result.put("messageCode", "90001");
		}catch(SystemException e){
			logger.error(e.getMessage(), e);
			result.put("messageCode", "90002");
		}catch(Exception e){
			logger.error("调用后台服务失败, 未知错误", e);
			result.put("messageCode", "90002");
		}
		result.put("messageText", Constants.get(result.getString("messageCode")));
		long endTime = System.currentTimeMillis();
		logger.debug("Access get Function end, time:"+(endTime-startTime));
		return Response.status(200).entity(result.toString()).build();
	}
	
	@POST
    @Path(value = "/upload")  
    @Consumes("multipart/form-data")  
	public Response upload(MultipartFormDataInput formDataInput){
		Map<String, List<InputPart>> uploadForm = formDataInput.getFormDataMap();
		InputStream input = null;
		String filename = null;
		String fileFullName = null;
		try {
			List<InputPart> inputParts = uploadForm.get("file");
			filename = uploadForm.get("filename").get(0).getBodyAsString();
			long filelength = Long.valueOf(uploadForm.get("filelength").get(0).getBodyAsString());
			if(inputParts != null && inputParts.size() > 0){
				InputPart inputPart = inputParts.get(0);
				input = inputPart.getBody(InputStream.class, null);
				filename = System.currentTimeMillis()+filename;
				fileFullName = Constants.get("oss.bucket.remote.path")+"/"+filename;
				ossBackup.putObject(input, Constants.get("oss.bucket.remote.path"), filename, filelength);
			}
		} catch (Exception e) {
			logger.error("上传图片失败");
			return Response.status(200).entity(new ResponseResult("90002", "上传图片失败")).build();
		}
		return Response.status(200).entity(new ResponseResult("10000", "", fileFullName).toString()).build();
	}
	
	@GET
    @Path("/{path}/{filename}")  
    @Produces("image/jpeg")  
	public Response download(@PathParam("path") String path, @PathParam("filename") String filename){
		try {
			InputStream input = ossBackup.getObject(path+"/"+filename);
			ResponseBuilder builder = Response.ok(input);
			builder.header("Content-Disposition", "attachment; filename="+filename);
			return builder.build();
		} catch (Exception e) {
			logger.error("下载图片失败", e);
		}
		return null;
	}
	
}
